#!/usr/bin/python

# Importing Python Modules
import time
import threading
import logging

# Importing My Modules
import readconfig
import updateserver
import servercontrol

# Declaring Globals
us = updateserver
intStartServer = int(readconfig.readConfig(option = "startServer"))
intNumberServers = int(readconfig.readConfig(option = "numberServers"))


logging.basicConfig(level=logging.DEBUG,
                    format='(%(threadName)-10s) %(message)s',
                    )


def restartOfflineServersEvent(e1):
    """Wait for the event to be set before starting servers"""
    while True:
        logging.debug('Wait for signal(event) before starting')
        e1.wait()
        event_is_set = e1.isSet()
        logging.debug('event1 set: %s ', event_is_set)
        for i in range(intNumberServers):
            num = i + 1
            servercontrol.startServerThread(num, e3)
            time.sleep(5)
        e1.clear()

def updateAllServersEvent(e2):
    """wait for the event to be set before updating servers"""
    logging.debug('Wait for signal(event) before updating')
    while True:
        e2.wait()
        event_is_set = e2.isSet()
        logging.debug('Event2 set: %s', event_is_set)
    
        strOutput = us.updateServer()
        if us.checkIfAlreadyUpdated(strOutput) == False:
            e3.clear()
            logging.debug("e3 Event is now set to False")
            for i in range(intNumberServers):
                num = i + 1
                servercontrol.stopServer(num, e3)
                continue
            logging.debug("stopServer() finished")
        if e3.isSet() == False:
            e3.set()
        time.sleep(600)


e1 = threading.Event()
e2 = threading.Event()
e3 = threading.Event()

t1 = threading.Thread(name='startAllServers',
                      target=restartOfflineServersEvent,
                      args=(e1,))

t2 = threading.Thread(name='updateAllServers',
                      target=updateAllServersEvent,
                      args=(e2,))

t1.start()
t2.start()

e1.set()
logging.debug('Event 1 is set')
e2.set()
logging.debug('Event 2 is set')
e3.set()
logging.debug('Event 3 is set')
